package com.enation.app.javashop.core.promotion.pintuan.service.impl;

import com.enation.app.javashop.core.member.model.dos.LeaderDO;
import com.enation.app.javashop.core.member.model.dos.MemberAddress;
import com.enation.app.javashop.core.member.service.LeaderManager;
import com.enation.app.javashop.core.promotion.pintuan.exception.PintuanErrorCode;
import com.enation.app.javashop.core.promotion.pintuan.model.PinTuanGoodsVO;
import com.enation.app.javashop.core.promotion.pintuan.service.PintuanCartManager;
import com.enation.app.javashop.core.promotion.pintuan.service.PintuanGoodsManager;
import com.enation.app.javashop.core.promotion.pintuan.service.PintuanOrderManager;
import com.enation.app.javashop.core.shop.model.dto.FixTimeSection;
import com.enation.app.javashop.core.shop.service.ShopManager;
import com.enation.app.javashop.core.shop.service.impl.OrderReceiveTimeManager;
import com.enation.app.javashop.core.trade.cart.model.enums.CartSourceType;
import com.enation.app.javashop.core.trade.cart.model.vo.CartSkuVO;
import com.enation.app.javashop.core.trade.cart.model.vo.CartView;
import com.enation.app.javashop.core.trade.order.model.dto.OrderDTO;
import com.enation.app.javashop.core.trade.order.model.enums.OrderTypeEnum;
import com.enation.app.javashop.core.trade.order.model.enums.ShipTypeEnum;
import com.enation.app.javashop.core.trade.order.model.vo.CheckoutParamVO;
import com.enation.app.javashop.core.trade.order.model.vo.TradeVO;
import com.enation.app.javashop.core.trade.order.service.TradeCreator;
import com.enation.app.javashop.core.trade.order.service.impl.DefaultTradeCreator;
import com.enation.app.javashop.core.trade.order.service.impl.TradeManagerImpl;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.security.model.Buyer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


/**
 * Created by kingapex on 2019-01-24.
 * 拼团交易业务类<br/>
 * 继承默认的交易业务类<br/>
 * 其中不同的是:<br/>
 * 1、使用 {@link PintuanCartManager} 获取购物车内容<br/>
 * 2、不检测优惠活动的合法性，因为拼团不存在其它活动的重叠
 * @author kingapex
 * @version 1.0
 * @since 7.1.0
 * 2019-01-24
 */
@Service
public class PintuanTradeManagerImpl extends TradeManagerImpl {

    @Autowired
    private PintuanCartManager  pintuanCartManager;

    @Autowired
    private PintuanOrderManager pintuanOrderManager;

    @Autowired
    private PintuanGoodsManager pintuanGoodsManager;

    @Autowired
    protected LeaderManager leaderManager;

    @Autowired
    private OrderReceiveTimeManager orderReceiveTimeManager;

    @Autowired
    private ShopManager shopManager;

    protected final Log logger = LogFactory.getLog(this.getClass());

    /**
     * 创建订单并创建拼团订单
     * @param client 客户端类型
     * @param pinTuanOrderId 拼团订单id，如果为空创建拼团，如果不为空参团
     * @return 交易单VO
     */
    public TradeVO createTrade(String client, Integer pinTuanOrderId, Integer receiveTimeSeq, double walletPayPrice) {

        // 1.自己参与自己拼团的判定
        if (pinTuanOrderId != null) {
            Buyer buyer = UserContext.getBuyer();
            this.pintuanOrderManager.getModel(pinTuanOrderId).getParticipants().forEach(participant -> {
                if (participant.getId().equals(buyer.getUid())) {
                    throw new ServiceException(PintuanErrorCode.E5013.code(), "你已经参加过这次拼团了");
                }
            });
        }

        // 2.设置客户的类型
        super.setClientType(client);
        // 3.结算参数
        CheckoutParamVO param = checkoutParamManager.getParam();
        // 4.拼团商品购物车
        CartView cartView = pintuanCartManager.getCart();

        Integer sellerId = cartView.getCartList().get(0).getSellerId();

        if(CollectionUtils.isEmpty(cartView.getCartList())){
            return null;
        }
        // 5.用户默认地址
        MemberAddress memberAddress = this.memberAddressClient.getModel(param.getAddressId());

        // 6.查询团长信息
        String activeShipWay = cartView.getTotalPrice().getActiveShipWay();

        LeaderDO leaderDO = leaderManager.getLeaderDO(param, memberAddress, activeShipWay);

        logger.info("准备创建拼团订单");
        logger.info("param:" + param);
        logger.info("cartView:" + cartView);
        logger.info("memberAddress:" + memberAddress);

        TradeCreator tradeCreator = new DefaultTradeCreator(param, cartView, memberAddress)
                .setTradeSnCreator( tradeSnCreator)
                .setGoodsClient(goodsClient)
                .setMemberClient(memberClient)
                .setShippingManager(shippingManager);

        //和普通的交易不同，不用检测活动的合法性，因为拼团不会存在活动的重叠
        //检测配送范围-> 检测商品合法性 -> 创建交易
        TradeVO tradeVO = tradeCreator.checkGoods().createTrade();
        OrderDTO order = tradeVO.getOrderList().get(0);
        order.setOrderType(OrderTypeEnum.pintuan.name());
        if (shopManager.checkIsShetuan(sellerId)) {
            order.setIsShetuan(1);
        }
        // 获取用户指定配送时间
        FixTimeSection timeSection = orderReceiveTimeManager.getReceiveTimeBySeller(sellerId,receiveTimeSeq);
        // 中间处理社区团购还是商城的拼团信息
        order.setShippingType(activeShipWay);
        if (activeShipWay.equals(ShipTypeEnum.SELF.name()) && leaderDO!=null) {
            order.setLeaderId(leaderDO.getLeaderId());
            order.setPickAddr(leaderDO.getProvince() + leaderDO.getCity() + leaderDO.getTown() + leaderDO.getAddress());
        }
        // 拼团订单收货时间
        //order.setReceiveTime(timeSection.getReceiveTimeStamp());
        CartSkuVO cartSkuVO = cartView.getCartList().get(0).getSkuList().get(0);
        PinTuanGoodsVO detail = this.pintuanGoodsManager.getDetail(cartSkuVO.getSkuId());
        order.setReceiveTime(detail.getPickTime());
        order.setReceiveTimeType(timeSection.getReceiveTimeType());

        logger.info("生成交易："+ tradeVO);
        tradeVO.setCartSourceType(CartSourceType.SHETUAN_CART.name());
        tradeVO.setWalletPayPrice(walletPayPrice);
        //订单入库
        this.tradeIntodbManager.intoDB(tradeVO);

        //创建拼团订单
        OrderDTO orderDTO  = tradeVO.getOrderList().get(0);
        CartSkuVO skuVO = cartView.getCartList().get(0).getSkuList().get(0);

        pintuanOrderManager.createOrder(orderDTO, skuVO.getSkuId(), pinTuanOrderId);

        return tradeVO;
    }
}
